<?php
namespace App\Repositories\BLL\Wechat;
use Illuminate\Support\Facades\DB;
use EasyWeChat\Foundation\Application;
use App\Repositories\BLL\WechatUserBLL;

class EventBLL
{
	private $userBLL,$UserService;
	public function __construct(WechatUserBLL $user,Application $wechat){
		$this->userBLL = $user;
		$this->UserService = $wechat->user;
	}

	public function receiveEvent($message){
		$res="";
		switch ($message->Event) {
            case 'subscribe':
                //关注
                $EventKey = $message->EventKey;
				//获取用户信息
				$user = $this->UserService->get($message->FromUserName);
				$user = json_decode(json_encode($user),TRUE);
				if($EventKey !== null){
					$EventKey = str_replace("qrscene_","",$EventKey);
					//查询微信墙
					$wall = DB::table('walls')
								->where([['id','=',$EventKey],['failure_date','>=',date('Y-m-d')]])
								->first();
					if($wall){
						$user['wallid'] = $EventKey;
						$res = '欢迎参加'.$wall->title.'，直接在微信公众号发送祝福吧!';
					}
				}
				if($res == ""){
					//查询关注返回
	                $welcome = DB::table('keywords')
	                				->where('type', '=', 1)
								->select('value')
								->first();
					if($welcome){
						$res = $welcome->value;
					}else{
						$res = "欢迎关注！";
					}
					//写入待发送记录
					$msgRule = DB::table('msg_rules')
								->where('type','=',1)
								->get();
					$msgLogArray = array();
					$now = date("Y-m-d H:i:s",time());
					foreach($msgRule as $v){
						//计算发送时间
						$min = $v->minute;
						$sendTime = date('Y-m-d H:i:s',strtotime("$now+$min min"));
						$msgLogArray[] = ['openid'=>$message->FromUserName,'sendtime'=>$sendTime
											,'msg'=>$v->msg,'created_at'=>$now,'updated_at'=>$now];
					}
					DB::table('msg_logs')->insert($msgLogArray);
				}
				//用户信息写入DB
				if(!$this->userBLL->updateUser($user)){
					$res = "欢迎关注，但是信息写入失败，请联系技术人员解决";
				}
                break;
			case 'SCAN':
				//扫码
				$EventKey = $message->EventKey;
				//获取用户信息
				$user = $this->UserService->get($message->FromUserName);
				$user = json_decode(json_encode($user),TRUE);
				//查询微信墙
				$wall = DB::table('walls')
							->where([['id','=',$EventKey],['failure_date','>=',date('Y-m-d')]])
							->first();
				$user['wallid'] = $EventKey;
				$res = '欢迎参加'.$wall->title.'，直接在微信公众号发送祝福吧!';
				//用户信息写入DB
				if(!$this->userBLL->updateUser($user)){
					$res = "欢迎关注，但是信息写入失败，请联系技术人员解决";
				}
				break;
			case 'unsubscribe':
				//取消关注
				//删除待发送信息
				DB::table('msg_logs')
					->where([
						['openid', '=', $message->FromUserName],
						['status', '=', 0],
					])
					->update(['status' => 3]);

				break;
            default:
                //其他
                $res = "";
                break;
        }

		return $res;
	}
}
